<template>
    <Modal v-model="modal.show" width="30" :mask-closable="false" class="login-modal" footer-hide>
        <div class="login-box-top">
            <h1>{{modal.title}}</h1>
        </div>
        <div class="login-input">
            <Form ref="loginForm" :model="loginForm" :rules="enterrules" class="login-form">
                <FormItem prop="username">
                    <Input class="user" v-model="loginForm.username" size="large" :placeholder="$t('enterusername')">
                    </Input>
                </FormItem>
                <FormItem prop="password">
                    <Input class="pass" :type="!passType ? 'password' : 'text'" password v-model="loginForm.password"
                        size="large" :placeholder="$t('enterpassword')" autocomplete="new-password">
                    <div slot="suffix" @click="setPassType">
                        <Icon type="ios-eye-outline" v-if="passType" />
                        <Icon type="ios-eye-off-outline" v-else />
                    </div>
                    </Input>
                </FormItem>
                <FormItem prop="captcha" class="yanzhengma" style="display:flex;" ref="captcha">
                    <Input class="verify" v-model="loginForm.captcha" size="large"
                        :placeholder="$t('Verificationcode')">
                    </Input>
                    <div style="line-height: 0;flex:0 0 94px;">
                        <Tooltip :content="$t('updateverificationcode')" placement="top" theme="dark" :disabled="loginLoading">
                            <img style="width: 100%;" :style="{cursor: loginLoading ? 'not-allowed' : 'pointer'}" :src="yzmPic" :alt="$t('Verificationcode')"
                               @error="setDefYzm" @click="getVerification()" v-show="showYzm"/>
                        </Tooltip>
                    </div>
                </FormItem>
                <FormItem>
                    <div class="check-wrapper">
                      <div>
                        <Checkbox v-model="remerberToken"></Checkbox>
                            {{$t('rememberMe')}}
                      </div>
<!--                      <div class="register-btn" @click="changeForm('register')">-->
<!--                        邮箱注册-->
<!--                      </div>-->
                        <!-- <span v-if="readMeCopy">
                            <Checkbox v-model="readMeCopy" disabled></Checkbox>我已阅读并同意
                        </span><span class="text" @click="agreementModel = true">《奇安信隐私政策声明》</span> -->
                    </div>
                </FormItem>
                <FormItem class="submit">
                    <Button class="login-btn" type="primary" long size="large" :loading="loginLoading"
                        @click="loginButton('loginForm')">{{ $t('capitalLogin') }}</Button>
                </FormItem>
            </Form>
        </div>
    </Modal>
</template>

<script>
    import encryption from '@/libs/encryption.js';
    import cookieUse from '@/libs/cookie.js';
    import { login, verCode} from '@/api/login.js';
    import { mapState,mapActions } from 'vuex';
    import {debounce} from '@/libs/utils'
    export default {
        name: 'login',
        props:['changeForm'],
        mixins: [],
        data() {
            return {
                timeout:-1,
                showYzm:false,
                modal: {
                    show: false,
                    title: '欢迎登录'
                },
                validate: {
                    user: true,
                    userPrompt: '',
                    pwd: true,
                    pwdPrompt: '',
                    yzm: true,
                    yzmPrompt: ''
                },
                remerberToken: true,
                // loginLoading: false,
                // yzmPic: '',
                loginForm: {
                    passwordInputType: 'password',
                    username: '',
                    password: '',
                    captcha: ''
                },
                enterrules: {
                    username: [
                        { required: true, type: 'string', message: '用户名不能为空', trigger: 'change' },
                        { type: 'string', min: 5, message: '用户名长度不能小于5个字符', trigger: 'change' },
                        { type: 'string', max: 30, message: '用户名长度不能大于30个字符', trigger: 'change' }
                    ],
                    password: [{ required: true, type: 'string', message: '密码不能为空', trigger: 'change' }],
                    captcha: [{ required: true, type: 'string', message: '验证码不能为空', trigger: 'change' }]
                },
                // icon
                defYzm: require('../../assets/login/defYzm.png'),
                setDefYzm:(event) =>  {
                    let img = event.srcElement;
                    img.src = this.defYzm;
                    img.onerror = null;
                },
                //眼睛状态
                passType: false,
                //协议
                agreementModel: false,
                readMe: false,
                readMeCopy: false
            };
        },
        computed:{
            ...mapState('login',['t','key','salt','iv','loginLoading']),
            yzmPic(){
                if(this.t){
                    return `${this.baseURL}/identity/anonymity/captcha?t=${this.t}`
                }else{
                    return this.defYzm
                }
            }
        },
        watch:{
            t(val){
                this.loginForm.captcha = '';
            }
        },
        mounted() {
            //绑定事件
            this._loginForm = {...this.loginForm};
            window.addEventListener('keydown', this.keyDown);
            this.verification();
            this.timeout = setTimeout(()=>{
              this.showYzm = true
            },500)
          
        },
        destroyed() {
            clearTimeout(this.timeout)
            window.removeEventListener('keydown', this.keyDown, false);
        },
        methods: {
            ...mapActions('login',['verification']),
            resetFormItem(formRef,prop){
                this.$refs[formRef].fields.forEach(function (e) {
                    if (e.prop === prop) {
                        e.resetField()
                    }
                })
            },
            openModal(){
                // 验证码
                this.verification();
                this.modal.show = true;
                this.loginForm = {...this._loginForm};
                this.$refs.loginForm.resetFields();
            },
            closeModal(){
              this.modal.show = false;
            },
            // 验证码
            // verification() {
            //     let _this = this;
            //     verCode()
            //         .then((res) => {
            //             if (res.data.code === 1) {
            //                 let getData = res.data.data;
            //                 let codeArr = [];
            //                 for (let key in getData) {
            //                     codeArr.push(getData[key]);
            //                 }
            //                 codeArr.sort();
            //                 const t = getData['t'];
            //                 const key = codeArr[0];
            //                 const salt = codeArr[1];
            //                 const iv = codeArr[2];
            //                 _this.loginForm.t = t;
            //                 _this.loginForm.key = key;
            //                 _this.loginForm.salt = salt;
            //                 _this.loginForm.iv = iv;
            //                 _this.yzmPic = `${this.baseURL}/identity/anonymity/captcha?t=${t}`;
            //                 _this.loginForm.captcha = '';
            //             } else {
            //                 _this.yzmPic = _this.defYzm;
            //             }
            //         })
            //         .catch((err) => {
            //             _this.yzmPic = _this.defYzm;
            //             console.log(err);
            //         });
            // },
            getVerification(){
                !this.loginLoading && this.verification()
            },
            setPassType() {
                this.passType = !this.passType;
            },
            // 点击显示密码
            showPassword() {
                if (this.loginForm.passwordInputType === 'text') {
                    this.loginForm.passwordInputType = 'password';
                } else {
                    this.loginForm.passwordInputType = 'text';
                }
            },
            // 用户登录
            keyDown(e) {
                //如果是回车则执行登录方法
                if (e.keyCode == 13) {
                    this.loginButton();
                }
            },
            // 登录
            loginButton:debounce(function() {
                let _this = this;
                _this.$store.commit('login/setLoginLoading',true);
                // _this.loginLoading = true;
                function trimStr(str) {
                    return str.replace(/(^\s*)|(\s*$)/g, '');
                }
                this.$refs['loginForm'].validate((valid) => {
                    if (valid) {
                        let UserName = trimStr(this.loginForm.username);
                        let PassWord = trimStr(this.loginForm.password);
                        let key = encryption.CryptoJS.enc.Utf8.parse(this.key);
                        let iv = encryption.CryptoJS.enc.Utf8.parse(this.iv);
                        let salt = encryption.CryptoJS.enc.Utf8.parse(this.salt);
                        PassWord = encryption.Encrypt(PassWord, key, iv, salt);
                        let params = {
                            password: PassWord,
                            username: UserName,
                            rememberMe: this.remerberToken,
                            t: this.t,
                            captcha: this.loginForm.captcha
                        };
                        login(JSON.stringify(params))
                            .then((res) => {
                                if (res.data.code === 1) {
                                    let token = res.data.data;
                                    let langModel = 'zh';
                                    // if (this.langText === 'English') {
                                    //     langModel = 'zh';
                                    // } else {
                                    //     langModel = 'en';
                                    // }
                                    if (this.remerberToken) {
                                        cookieUse.setCookie('desig-token', token, 168);
                                        cookieUse.setCookie('desig-lang', langModel, 168);
                                        cookieUse.setCookie('Authorization', token, 168);
                                    } else {
                                        cookieUse.setCookie('desig-token', token, 8);
                                        cookieUse.setCookie('desig-lang', langModel, 8);
                                        cookieUse.setCookie('Authorization', token, 8);
                                    }
                                    localStorage.setItem('token', token); // 为topo页面存储
                                    // 是否记住密码
                                    sessionStorage.setItem('desig-rm', this.remerberToken);
                                    this.$router.push({
                                        path: '/main'
                                    });
                                } else {
                                    this.$Message.error({
                                        content: res.data.message,
                                        duration: 3
                                    });
                                    // 更新验证码
                                    this.verification();
                                }
                            })
                            .catch((err) => {
                                console.log(err);
                                _this.$store.commit('login/setLoginLoading',false);
                                this.verification();
                            });
                    } else {
                        _this.$store.commit('login/setLoginLoading',false);
                    }
                });
            },500),
            // 切换语言
            // changeLang(){
            //     let val = ''
            //     if(this.langText === '中文'){
            //         val = 'zh'
            //         this.langText = 'English'
            //     }else {
            //         val = 'en'
            //         this.langText = '中文'
            //     }
            //     this.$i18n.locale = val
            //     cookieUse.setCookie('language-s',val)
            //     window.location.reload()
            // },
            cancelModal() {
                this.agreementModel = false;
                this.readMeCopy = true;
            }
        },
    };
</script>

<style scoped>
    .login-modal /deep/ .ivu-modal-content {
        border-radius: 8px;
        background: #fff;
    }

    .login-modal /deep/ .ivu-modal-body {
        padding: 12% 15%;
    }
    .login-modal /deep/ .ivu-modal-close{
      display: none;
    }

    

    .login-box-top {
        /* padding: 20px 40px; */
        /*color: #C81125;*/
        color: #1d252c;
        margin-bottom: 30px;
        text-align: center;
    }

    .login-form {
        /* padding: 20px 40px; */
    }

    .login-form .check-wrapper {
        display: flex;
        font-weight: bold;
        align-items: center;
        line-height: 1;
        color:#1d252c;
        justify-content: space-between;
    }
    .register-btn{
      cursor: pointer;
      border-bottom: 2px solid #1d252c;
    }

    .login-form .check-wrapper span.text {
        color: #3669c3;
        margin-top: -2px;
        cursor: pointer;
    }

    /deep/ .login-input .ivu-input-suffix {
        height: 26px;
        margin-top: 12px;
    }

    /deep/ .login-input .pass .ivu-input-suffix i.ivu-icon-ios-eye-off-outline:before {
        content: '';
        display: block;
        width: 20px;
        height: 20px;
        background: url('../../assets/login-qax/icon_by.png') no-repeat;
    }

    /deep/ .login-input .pass .ivu-input-suffix i.ivu-icon-ios-eye-outline:before {
        content: '';
        display: block;
        width: 20px;
        height: 20px;
        background: url('../../assets/login-qax/icon_open.png') no-repeat;
    }
    .submit{
        margin-bottom:0;
    }
    /deep/ .submit button,.submit button:hover {
        height: 46px!important;
        background: #3669c3!important;
        border-radius: 0px!important;
    }

    /deep/ .login-input .ivu-input {
        height: 46px;
        color: #1d252c !important;
        border-radius: 0px;
        background: #F7F9FB;
        border-radius: 0px 0px 0px 0px;
        border: 1px solid #EBEEF2;
    }

    /deep/ .login-input .ivu-input::-webkit-input-placeholder {
        color: #535D6D !important;
    }

    /deep/ .login-input .ivu-input:hover {
        border: 1px solid #EBEEF2;
    }

    /deep/ .login-input .ivu-input:focus {
        box-shadow: none !important;
        /*box-shadow:0px 0px 8px rgb(167, 153, 218);
        border: 1px solid rgb(167, 153, 218);
        color: rgb(167, 153, 218)!important;*/
    }

    /deep/ .login-input .ivu-form-item-error .ivu-input {
        border: 1px solid #ed4014;
    }

    /deep/ .login-input .ivu-form-item-error .ivu-input:focus {
        /* border: 1px solid #ed4014; */
        box-shadow: 0px 0px 8px rgb(237, 64, 20, 0.6);
    }

    /deep/ .verify {
        flex: auto;
        margin-right: 10px;
    }

    /deep/ .yanzhengma .ivu-form-item-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
    }

    /deep/ .ivu-btn-primary {
        color: #fff !important;
    }

    .langWrap .ivu-btn-ghost.ivu-btn-dashed {
        color: rgba(255, 255, 255, 0.6);
        border-color: rgba(255, 255, 255, 0.6);
    }

    .langWrap .ivu-btn-ghost.ivu-btn-dashed:hover {
        color: #57a3f3;
        border-color: #57a3f3;
    }

    .login-btn {
        background: #1D252C;
    }

    .argument-wrapper {
        /*font-size:14px;*/
    }

    .argument-header {
        margin-bottom: 10px;
        font-size: 14px;
        text-align: center;
        font-weight: bold;
    }

    .argument-content {
        line-height: 1.5;
        height: 50vh;
        overflow: auto;
        font-size: 12px;
    }

    .argument-footer-wrapper {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 10px;
    }

    .argument-footer-wrapper .check-wrapper {
        display: flex;
        color: #666666;
    }

    .comfirm-btn {
        background: #2e6be6;
        color: #fff;
    }

    .comfirm-btn:disabled {
        opacity: 0.3;
    }

    .comfirm-btn:disabled:hover {
        background: #2e6be6;
        color: #fff;
        opacity: 0.3;
    }

    .comfirm-btn {
        background: #2e6be6;
        color: #fff;
    }
</style>
<style>
    #login-page .login-input .ivu-input {
        color: #fff !important;
    }

    #login-page .login-input .ivu-input::-webkit-input-placeholder {
        color: rgba(255, 255, 255, 0.3) !important;
    }

    #login-page .ivu-checkbox-checked .ivu-checkbox-inner {
        border-color: transparent;
    }

    .argument-content p {
        margin: 10px 0;
    }

    .argument-content td {
        padding: 5px;
    }
</style>
